//
//  HNSH_CartShopViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/3/2.
//

#define BottomViewHeight    50

#import "HNSH_CartShopViewController.h"

//view
#import "HNSH_CartShopCell.h"
#import "HNSH_CartShopHeader.h"
#import "HNSH_CartShopFooter.h"
#import "HNSH_CartShopBottomView.h"

//vc
#import "HNSH_ShopDetailViewController.h"       //商家
#import "HNSH_ConfirmOrderViewController.h"     //确认订单

@interface HNSH_CartShopViewController ()<DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

/* listAry */
@property (nonatomic, strong) NSArray *listAry;

/* bottomView */
@property (nonatomic, strong) HNSH_CartShopBottomView *bottomView;

/* editButton */
@property (nonatomic, strong) UIButton *editButton;

/* changeStatusAry */
@property (nonatomic, strong) NSMutableArray *changeStatusAry;

@end

static NSString *HNSH_CartShopCellID = @"HNSH_CartShopCellID";
static NSString *HNSH_CartShopHeaderID = @"HNSH_CartShopHeaderID";
static NSString *HNSH_CartShopFooterID = @"HNSH_CartShopFooterID";

@implementation HNSH_CartShopViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadGoodsCartList];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self configTopView];
    
    [self configTableView];
}

#pragma mark networking
- (void)loadGoodsCartList {
    [HNSH_ShopNetServer requestGoodsCartListSuccess:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self successWithData:responseObject];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//更新状态
- (void)loadGoodsCartUpdateWithParams:(NSArray *)params {
    [HNSH_ShopNetServer requestGoodsCartUpdateWithParams:@{@"items":params} success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self successWithData:responseObject];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

- (void)loadGoodsCartDelete {
    NSMutableArray *ary = [NSMutableArray arrayWithCapacity:0];
    for (HNSH_CartShopModel *model in self.listAry) {
        for (HNSH_CartShopItemModel *item in model.items) {
            if (item.selected) {
                [ary addSafeObject:item.uid];
            }
        }
    }
    [HNSH_ShopNetServer requestGoodsCartDeleteWithCartIds:ary success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self successWithData:responseObject];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//数据请求成功统一处理
- (void)successWithData:(ST_BaseNetModel * _Nullable)responseObject {
    self.listAry = [NSArray yy_modelArrayWithClass:[HNSH_CartShopModel class] json:responseObject.resultset[@"list"]];
    
    BOOL isAll = YES;
    CGFloat money = 0.00;
    for (HNSH_CartShopModel *model in self.listAry) {
        if (!model.selected) {
            isAll = NO;
        }
        for (HNSH_CartShopItemModel *item in model.items) {
            if (item.selected) {
                money = money + [item.price doubleValue] * item.quantity;
            }
        }
    }
    self.bottomView.moneyString = [NSString stringWithFormat:@"%.2f",money];
    self.bottomView.selectButton.selected = isAll;
    [self.tableView reloadData];
}

#pragma mark event
- (void)configParamsWithModel:(id)model {
    if ([model isKindOfClass:[HNSH_CartShopItemModel class]]) {
        NSLog(@"点击商品");
        HNSH_CartShopItemModel *item = model;
        NSDictionary *dict = @{@"cart_id":item.uid,
                               @"quantity":@(item.quantity),
                               @"selected":@(item.selected),
        };
        [self loadGoodsCartUpdateWithParams:@[dict]];
    }
    if ([model isKindOfClass:[HNSH_CartShopModel class]]) {
        NSLog(@"点击头部全选");
        HNSH_CartShopModel *itemsMolde = model;
        NSMutableArray *ary = [NSMutableArray arrayWithCapacity:itemsMolde.items.count];
        for (HNSH_CartShopItemModel *item in itemsMolde.items) {
            NSDictionary *dict = @{@"cart_id":item.uid,
                                   @"quantity":@(item.quantity),
                                   @"selected":@(item.selected),
            };
            [ary addSafeObject:dict];
        }
        [self loadGoodsCartUpdateWithParams:ary];
    }
    [self.tableView reloadData];
}

#pragma mark lazy
- (HNSH_CartShopBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[HNSH_CartShopBottomView alloc]init];
    }
    return _bottomView;
}

- (NSMutableArray *)changeStatusAry {
    if (!_changeStatusAry) {
        _changeStatusAry = [NSMutableArray arrayWithCapacity:0];
    }
    return _changeStatusAry;
}

- (UIButton *)editButton {
    if (!_editButton) {
        _editButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _editButton.frame = CGRectMake(kScreenWidth-72, kStatusBarHeight, 72, 44);
        [_editButton setTitle:@"管理" forState:UIControlStateNormal];
        [_editButton setTitle:@"完成" forState:UIControlStateSelected];
        [_editButton setTitleColor:[UIColor appBlackLabelColor] forState:UIControlStateNormal];
        _editButton.titleLabel.font = [UIFont systemFontOfSize:16];
        WeakSelf(weakSelf);
        [[_editButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            UIButton *button = x;
            button.selected = !button.selected;
            weakSelf.bottomView.isEdit = button.isSelected;
            [weakSelf.tableView reloadData];
        }];
    }
    return _editButton;
}

#pragma mark configUI
- (void)configTopView {
    UIImageView *imgV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 158)];
    imgV.image = [UIImage imageNamed:@"shop_cart_nav_bg"];
    [self.view addSubview:imgV];
    [self.view sendSubviewToBack:imgV];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, kStatusBarHeight+10, 200, 25)];
    titleLabel.text = @"购物车";
    titleLabel.textColor = [UIColor appBlackLabelColor];
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [self.view addSubview:titleLabel];
    
    [self.view addSubview:self.editButton];
    
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(BottomViewHeight);
    }];
    
    WeakSelf(weakSelf);
    //全选
    [[self.bottomView.selectButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(UIButton *x) {
        UIButton *button = x;
        button.selected = !button.selected;
        
        if (weakSelf.listAry.count <= 0) {
            return;
        }
        
        NSMutableArray *ary = [NSMutableArray arrayWithCapacity:0];
        for (HNSH_CartShopModel *model in weakSelf.listAry) {
            [model headerChangeSelectedStatus:button.isSelected];
            for (HNSH_CartShopItemModel *item in model.items) {
                NSDictionary *dict = @{@"cart_id":item.uid,
                                       @"quantity":@(item.quantity),
                                       @"selected":@(item.selected),
                };
                [ary addSafeObject:dict];
            }
        }
        [weakSelf loadGoodsCartUpdateWithParams:ary];
    }];
    //创建订单
    self.bottomView.payBlock = ^{
        if (weakSelf.editButton.isSelected) {//删除
            [HNSH_AlertView showTitle:@"确认将该商品删除?" des:@"" buttonTitle:@"确认" buttonColor:[UIColor appRedLabelColor] buttonClick:^{
                [weakSelf loadGoodsCartDelete];
            }];
        } else {//购买
            BOOL isHave = NO;
            for (HNSH_CartShopModel *model in weakSelf.listAry) {
                for (HNSH_CartShopItemModel *item in model.items) {
                    if (item.selected) {
                        isHave = YES;
                    }
                }
            }
            if (!isHave) {
                [weakSelf.view makeToast:@"请选择商品"];
                return;
            }
            HNSH_ConfirmOrderViewController *vc = [[HNSH_ConfirmOrderViewController alloc]init];
            vc.from_cart = 1;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    };
}

- (void)configTableView {
    self.view.backgroundColor = [UIColor appWhiteLabelColor];
    
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(kNavBarAndStatusBarHeight, 0, BottomViewHeight, 0));
    }];
    [self setupEmpty:self.tableView image:[UIImage imageNamed:@"empty_list_data"] title:@""];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.rowHeight = 104;
    [self.tableView registerClass:[HNSH_CartShopCell class] forCellReuseIdentifier:HNSH_CartShopCellID];
    [self.tableView registerClass:[HNSH_CartShopHeader class] forHeaderFooterViewReuseIdentifier:HNSH_CartShopHeaderID];
    [self.tableView registerClass:[HNSH_CartShopFooter class] forHeaderFooterViewReuseIdentifier:HNSH_CartShopFooterID];
    
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
}

#pragma mark - 空数据处理 DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"empty_list_data"];
}

- (BOOL)emptyDataSetShouldFadeIn:(UIScrollView *)scrollView{
    return YES;
}


#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.listAry.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    HNSH_CartShopModel *item = self.listAry[section];
    return item.items.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 52.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 16.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    HNSH_CartShopFooter *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HNSH_CartShopFooterID];
    return footer;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    HNSH_CartShopHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HNSH_CartShopHeaderID];
    header.model = self.listAry[section];
    WeakSelf(weakSelf);
    header.reloadBlock = ^(HNSH_CartShopModel * _Nonnull haaderModel) {
        [weakSelf configParamsWithModel:haaderModel];
    };
    header.headerBlock = ^(NSString * _Nonnull shopId, NSString * _Nonnull shopName) {
        HNSH_ShopDetailViewController *vc = [[HNSH_ShopDetailViewController alloc]init];
        vc.shopId = shopId;
        vc.shopName = shopName;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    return header;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HNSH_CartShopModel *item = self.listAry[indexPath.section];
    HNSH_CartShopItemModel *model = item.items[indexPath.row];
    HNSH_CartShopCell *cell = [tableView dequeueReusableCellWithIdentifier:HNSH_CartShopCellID];
    cell.isEdit = self.editButton.isSelected;
    cell.model = model;
    cell.shopModel = item;
    WeakSelf(weakSelf);
    cell.reloadBlock = ^(HNSH_CartShopItemModel * _Nonnull cellModel) {
        [weakSelf configParamsWithModel:cellModel];
    };
    return cell;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
